package com.zhny.aiot.wn.weather.plugin;

import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.model.IRequestMessage;
import com.zhny.aiot.plugin.modbus.ModemEngine;
import com.zhny.aiot.plugin.modbus.device.ModemConfig;
import com.zhny.aiot.plugin.modbus.device.modbus.ModbusNumDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.TaskEntity;
import com.zhny.aiot.wn.weather.plugin.model.WNWeatherStoreEntry;

public class WNWeatherDevice extends ModbusNumDevice<WNWeatherStoreEntry> {
    public WNWeatherDevice(ModemEngine engine, IDeviceFactory<ModemConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super(engine, factory, centerFacilities, entity);
    }

    @Override
    public WNWeatherStoreEntry decode(ModemResponseMessage modemResponseMessage) {
        int temperature = modemResponseMessage.getData().readUnsignedShort ();
        int humidity = modemResponseMessage.getData().readUnsignedShort ();
        int illumination = modemResponseMessage.getData().readUnsignedShort ();
        int carbon = modemResponseMessage.getData().readUnsignedShort ();
        int soilTemperature = modemResponseMessage.getData().readUnsignedShort ();
        int soilHumidity = modemResponseMessage.getData().readUnsignedShort ();
        int conductivity = modemResponseMessage.getData().readUnsignedShort ();
        int ph = modemResponseMessage.getData().readUnsignedShort ();
        WNWeatherStoreEntry entry = new WNWeatherStoreEntry();
        entry.setTemperature (temperature == 0x7fff?"未接":String.format ("%.1f",temperature/10.0));
        entry.setHumidity (humidity == 0x7fff?"未接":String.format ("%.1f",humidity/10.0));
        entry.setIllumination (illumination == 0x7fff?"未接":String.format ("%d",illumination*10));
        entry.setCarbon (carbon == 0x7fff?"未接":String.format ("%d",carbon));

        entry.setSoilTemperature (soilTemperature == 0x7fff?"未接":String.format ("%.1f",soilTemperature/10.0));
        entry.setSoilHumidity (soilHumidity == 0x7fff?"未接":String.format ("%.1f",soilHumidity/10.0));
        entry.setConductivity (conductivity == 0x7fff?"未接":String.format ("%d",conductivity));
        entry.setPh (ph == 0xff?"未接":String.format ("%.2f",ph/100.00));
        return entry;
    }

    @Override
    public boolean checkError(ModemResponseMessage modemResponseMessage) {
        return modemResponseMessage.getData ().readableBytes () == 16;
    }

    @Override
    protected IRequestMessage getCommand(TaskEntity taskEntity) {
        return getFactory ().getRequestMessage (getConfig ());
    }

    @Override
    protected void disposable() {

    }
}
